/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bsc.war.form;

import bsc.ejb.metadata.Framework;
import bsc.ejb.metadata.NoteType;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author luisZavaleta
 */
public class NewNoteType extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("renderXml");
        try {

            boolean edit = false;
            Long noteTypeId = -1L;

            if (NumberUtils.isDigits(request.getParameter("id"))) {
                Long id = Long.valueOf(request.getParameter("id"));
                if (id >= 0) {
                    edit = true;
                    noteTypeId = id;
                }
            }


            HttpSession session = request.getSession();
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            NoteType notetype = (NoteType) Factory.getBean("NoteType");

            Framework framework = null;
            if (session.getAttribute("frameworkId") instanceof Long) {

                Long frameworkId = (Long) session.getAttribute("frameworkId");
                framework = (Framework) Factory.getBean("Framework");
                framework = delegate.findFramework(Long.valueOf(frameworkId));

            } else {
                throw new Exception("no hay frameworkId");
            }


            if (edit) {
                notetype = delegate.findNoteType(noteTypeId);
            } else {
                notetype = (NoteType) Factory.getBean("NoteType");
            }


            notetype.setDescription(request.getParameter("description"));
            notetype.setName(request.getParameter("name"));
            notetype.setFramework(framework);

            if (edit) {
                delegate.updateNoteType(notetype);
            } else {
                delegate.createNoteType(notetype);
            }

            mav.addObject("id", notetype.getIdNoteType());


        } catch (Exception e) {
        }
        return mav;

    }

}
